import ProductCategoryRow from "@/components/ProductCategoryRow";
import ProductRow from "@/components/ProductRow";
import type { Product } from "@/data/product";

interface ProductTableProps {
  products: Product[];
  filterText: string;
  inStockOnly: boolean;
}

function ProductTable({
  products = [],
  filterText,
  inStockOnly,
}: ProductTableProps) {
  // 存组件
  let rows: JSX.Element[] = [];
  let preCategory = "";

  products.forEach((product) => {
    if (
      product.name.toLowerCase().indexOf(filterText.trim().toLowerCase()) === -1
    )
      return;
    if (inStockOnly && !product.stocked) return;

    /**
     * 注意添加到rows数组的时候，元素要有一个key
     * 因为这也是列表渲染
     */
    if (product.category !== preCategory) {
      // 添加新的标题头
      rows.push(
        <ProductCategoryRow
          categoryName={product.category}
          key={product.category}
        />
      );
    }

    // 添加数据
    rows.push(<ProductRow product={product} key={product.name} />);
    preCategory = product.category;
  });

  return (
    <>
      <p>
        <span style={{ color: "red" }}>红色</span>表示已经没有库存
      </p>
      <table className="product-table">
        <thead>
          <tr>
            <th>Name</th>
            <th>Price</th>
          </tr>
        </thead>
        <tbody>{rows}</tbody>
      </table>
    </>
  );
}

export default ProductTable;
